$(function() {
	var topicTable = null;
	var opts = {
		targetId : "topicTable",
		templateId : "tabletopic",
		settings : {
			url : DI.queryTopic,
			ajaxType : "json",
			sourceInterface : {
				INum : "total",
				IData : "topicList"
			},
			paginationIndexName : {
				"peerpageRows" : "pageSize",
				"currentPage" : "pageNo"
			}
		},
		customFuncs : {
			delPop : function(delid) {
				popCtrl.confirmType = "del";
				popCtrl.deltopicId = delid;
				$("#popup_confirm").show();
			},
			modifyPop : function(row) {
				popCtrl.isAdd = false;
				popCtrl.modify = true;
				popCtrl.topicId = row.topicId;
				popCtrl.topicName = row.topicName;
				popCtrl.endTime = row.endTime;
				popCtrl.supViewTip = row.supViewTip;
				popCtrl.rejViewTip = row.rejViewTip;
				popCtrl.imgUrl = row.topicImg;
				$("#popup_cnt").show();
			},
			viewTopic : function(topicId) {
				var urlParam = location.host;
				if (urlParam.indexOf("sit") != -1
						|| urlParam.indexOf("dev") != -1) {
					window
							.open("http://djsit.cnsuning.com/sawp/contend/topic_index.html?topicId="
									+ topicId);
				} else if (urlParam.indexOf("pre") != -1) {
					window
							.open("http://djpre.cnsuning.com/sawp/contend/topic_index.html?topicId="
									+ topicId);
				} else {
					window
							.open("http://dj.suning.com/sawp/contend/topic_index.html?topicId="
									+ topicId);
				}

			}
		}

	};
	topicTable = SwiftUI.swiftTable.getInstance(opts);
	// 主区域
	var mainCtrl = avalon.define({
		$id : "mainController",
		topicKey : "",
		// 新增标签
		add : function() {
			popCtrl.isAdd = false;
			popCtrl.modify = false;
			popCtrl.topicId = "";
			popCtrl.topicName = "";
			popCtrl.endTime = "";
			popCtrl.supViewTip = "";
			popCtrl.rejViewTip = "";
			popCtrl.imgUrl = "";
			$("#popup_cnt").show();
		},
		searchData : function() {
			var searchParam = {
				"pageNo" : 1,
				"pageSize" : 10,
				"topicName" : mainCtrl.topicKey
			};
			topicTable.search(searchParam);
		}

	});
	// 弹框区域
	var popCtrl = avalon
			.define({
				$id : "popController",
				deltag : "",
				confirmType : "del",
				topicId : "",
				topicName : "",
				endTime : "",
				supViewTip : "",
				rejViewTip : "",
				imgUrl : "", // 上传后的图片url
				deltopicId : "",
				isAdd : false,
				modify : false,
				delTopic : function() {
					$.ajax({
						type : "post",
						dataType : "json",
						data : {
							"topicId" : popCtrl.deltopicId
						},
						url : DI.delTopic,
						success : function(data) {
							$("#popup_confirm").hide();
							if (data.retFlag == 1) {
								// searchTag();
								PLATFORM.showTips("success", "删除成功");
								// mainCtrl.tagList.remove(popCtrl.deltag);
								var searchParam = {
									"pageNo" : 1,
									"pageSize" : 10
								};
								topicTable.search(searchParam);
							} else {
								PLATFORM.showTips("error", data.errorMessage);
							}
						},
						error : function(err) {
							console.log(err);
						}
					});
				},
				save : function() {
					if (popCtrl.topicName == "") {
						$(".top-err").show().text("请输入话题主题");
						setTimeout(function() {
							$(".top-err").hide().text("");
						}, 2000);
						return;
					}
					if (popCtrl.endTime == "") {
						$(".top-err").show().text("请输入话题结束时间");
						setTimeout(function() {
							$(".top-err").hide().text("");
						}, 2000);
						return;
					}
					if (popCtrl.supViewTip == "" || popCtrl.rejViewTip == "") {
						$(".top-err").show().text("请输入是否词");
						setTimeout(function() {
							$(".top-err").hide().text("");
						}, 2000);
						return;
					}
					if (popCtrl.imgUrl == "") {
						$(".top-err").show().text("请先上传图片");
						setTimeout(function() {
							$(".top-err").hide().text("");
						}, 2000);
						return;
					}
					var imgurl = "";
					if (popCtrl.imgUrl.indexOf("http://") != -1) {
						imgurl = popCtrl.imgUrl;
					} else {
						imgurl = PLATFORM.imgprefix(DI.uploadImgPre
								+ popCtrl.imgUrl);
					}
					var data = {
						"topicName" : popCtrl.topicName,
						"endTime" : popCtrl.endTime,
						"topicImg" : imgurl,
						"supViewTip" : popCtrl.supViewTip,
						"rejViewTip" : popCtrl.rejViewTip
					};
					if (popCtrl.modify) {
						data = {
							"topicId" : popCtrl.topicId,
							"topicName" : popCtrl.topicName,
							"endTime" : popCtrl.endTime,
							"topicImg" : imgurl,
							"supViewTip" : popCtrl.supViewTip,
							"rejViewTip" : popCtrl.rejViewTip
						};
					}
					$.ajax({
						type : "post",
						dataType : "json",
						data : data,
						url : DI.saveTopic,
						success : function(data) {
							$("#popup_cnt").hide();
							if (data.retFlag == 1) {
								PLATFORM.showTips("success", "保存成功");
								var searchParam = {
									"pageNo" : 1,
									"pageSize" : 10
								};
								topicTable.search(searchParam);
							} else {
								PLATFORM.showTips("error", data.errorMessage);
							}
						},
						error : function(err) {
							console.log(err);
						}
					});
				},
				uploadImg : function() {
					// 调用上传图片接口
					var x = $("#preview-x").val(), y = $("#preview-y").val(), width = $(
							"#preview-width").val(), height = $(
							"#preview-height").val();

					var canvas = $('<canvas style="display:none;" width="'
							+ width + '" height="' + height + '"></canvas>')[0], ctx = canvas
							.getContext('2d');
					ctx.drawImage(imgObj, x, y, width, height, 0, 0, width,
							height);
					var data = canvas.toDataURL();
					// dataURL 的格式为
					// “data:image/png;base64,****”,逗号之前都是一些说明性的文字，我们只需要逗号之后的就行了
					data = data.split(',')[1];
					data = window.atob(data);
					var ia = new Uint8Array(data.length);
					for (var i = 0; i < data.length; i++) {
						ia[i] = data.charCodeAt(i);
					}
					;
					// canvas.toDataURL 返回的默认格式就是 image/png
					var blob = new Blob([ ia ], {
						type : "image/png"
					});
					var fd = new FormData();
					fd.append('image', blob);

					$.ajax({
						type : "post",
						dataType : "json",
						data : fd,
						url : DI.uploadMisc,
						contentType : false, // 不可缺
						processData : false, // 不可缺
						success : function(data) {
							if (data.retFlag == 1) {
								popCtrl.imgUrl = data.data;
								// PLATFORM.showTips("success", "保存成功");
							}
						},
						error : function(XMLHttpRequest, textStatus,
								errorThrown) {
							console.log(XMLHttpRequest);
						}
					});
				}
			});
	var cropper = null;
	// 图片裁剪
	var cropPreview = function() {
		cropper = new Cropper({
			aspectRatio : 'auto',
			element : document.getElementById('cropper-target'),
			previews : [ document.getElementById('preview-large') ],
			onCroppedRectChange : function(rect) {
				$("#preview-x").val(rect.left);
				$("#preview-y").val(rect.top);
				$("#preview-width").val(rect.width);
				$("#preview-height").val(rect.height);
			}
		});
		var input = document.getElementById('cropper-input');
		input.onchange = function() {
			popCtrl.isAdd = true;
			if (typeof FileReader !== 'undefined') {
				var reader = new FileReader();
				reader.onload = function(event) {
					cropper.setImage(event.target.result);
					var urlTxt = reader.result;
					setImageURL(urlTxt);
				};
				if (input.files && input.files[0]) {
					reader.readAsDataURL(input.files[0]);
				}
			} else { // IE10-
				input.select();
				input.blur();
				var src = document.selection.createRange().text;
				cropper.setImage(src);
			}
		};
	}
	var imgObj = new Image();
	;

	function setImageURL(urlTxt) {
		imgObj.src = urlTxt;
	}

	cropPreview();

	$("#endTime").datetimepicker({
		showSecond : true,
		timeFormat : 'hh:mm:ss'
	});
	avalon.scan();
});
